import { ElMessage, ElMessageBox } from 'element-plus'
import { getExportConfig, getMenunameByCode } from '@/api/report.js'
/* import * as pdfjs from 'pdfjs-dist'
import * as pdfjsWorker from 'pdfjs-dist/build/pdf.worker.entry.js' */
import { getLodop } from '@/assets/js/LodopFuncs.js'
import qs from 'qs'
import { getToken } from '@/utils/auth'
import { doPrintData } from '@/api/report'
let canvasImgs = [] // 渲染canvas的id数组

// 预览
export function doPreview(menuName) {
  // 获取菜单xml名称
  getMenunameByCode(menuName).then((res) => {
    const url = `/ureport/pdf/show?_u=slip-${res.data}`
    const iframe = window.frames['_print_pdf_frame']
    var a = document.getElementById('_print_pdf_frame')
    var iframeLoad = function () {
      iframe.window.focus()
      iframe.window.print()
    }
    if (!a.addEventListener) {
      a.attachEvent('onload', iframeLoad)
    }
    a.addEventListener('load', iframeLoad, true)
    iframe.window.focus()
    iframe.location.href = url
  })
}
async function updatePrintCount(callback, printCount) {
  callback && printCount && callback() // 增加打印次数
}
// 打印
export function doPrint(obj) {
  let { name, params = {}, callback, printCount, data = {} } = obj
  let _data = { ...params, ...data }
  let query = qs.stringify(params)
  //if (data && JSON.stringify(data) !== '{}') {
  // 传post数据
  try {
    // updatePrintCount(callback, printCount).then(() => {
    doPrintData({
      _u: `slip-${name}`,
      token: getToken(),
      query: params,
      ..._data,
    })
      .then((res) => {
        isPrint(res)
      })
      .catch((error) => {
        console.log(error)
      })
    // })
  } catch (error) {
    console.log(error)
  }
  /*  } else {
    isPrint()
  } */
  function isPrint(res) {
    let url =
      window.location.origin +
      `/ureport/pdf/show?_u=slip-${name}&token=${getToken()}&${query}`
    // 获取菜单xml名称
    if (res) {
      let blob = new Blob([res], {
        type: 'application/pdf',
      })
      url = URL.createObjectURL(blob)
    }
    printWithUrl(url)
    /* // 设置iframe样式
    let frameKey = 'fremekey-uni'
    // 如果存在则删除
    if (document.getElementById(frameKey)) {
      document.body.removeChild(document.getElementById(frameKey))
    }
    let _iframe = document.createElement('iframe')
    _iframe.setAttribute('id', frameKey)
    _iframe.setAttribute('name', frameKey)
    _iframe.setAttribute(
      'style',
      'position:absolute;width:0px;height:0px;left:-500px;top:-500px;'
    )

    document.body.appendChild(_iframe)
    const iframe = window.frames[frameKey]
    let a = document.getElementById(frameKey)
    console.log(iframe)
    console.log(a)
    let iframeLoadErrow = function () {
      ElMessage.warning('打印失败，请联系管理员')
    }
    let iframeLoad = function (e) {
      console.log(e)
      try {
        iframe.window.focus()
        iframe.window.print()
      } catch (error) {
        console.log(error)
        iframeLoadErrow()
      }
    }
    if (!a.addEventListener) {
      a.attachEvent('onload', iframeLoad)
    }
    a.addEventListener('load', iframeLoad, true)
    iframe.window.addEventListener('error', iframeLoadErrow, true)
    iframe.window.focus()
    console.log(url)
    iframe.location.href = url */
  }
}

export function printWithUrl(url) {
  // 设置iframe样式
  let frameKey = 'fremekey-print'
  // 如果存在则删除
  if (document.getElementById(frameKey)) {
    document.body.removeChild(document.getElementById(frameKey))
  }
  let _iframe = document.createElement('iframe')
  _iframe.setAttribute('id', frameKey)
  _iframe.setAttribute('name', frameKey)
  _iframe.setAttribute(
    'style',
    'position:absolute;width:0px;height:0px;left:-500px;top:-500px;'
  )
  document.body.appendChild(_iframe)
  const iframe = window.frames[frameKey]
  let fileFrameDom = document.getElementById(frameKey)
  let iframeLoadErrow = function () {
    ElMessage.warning('打印失败，请联系管理员')
  }
  let iframeLoad = function (e) {
    try {
      iframe.window.focus()
      iframe.window.print()
    } catch (error) {
      console.log(error)
      iframeLoadErrow()
    }
  }
  if (!fileFrameDom.addEventListener) {
    fileFrameDom.attachEvent('onload', iframeLoad)
  }
  fileFrameDom.addEventListener('load', iframeLoad, true)
  iframe.window.addEventListener('error', iframeLoadErrow, true)
  iframe.window.focus()
  console.log(url)
  iframe.location.href = url
}

// 静默打印
let renderTimes = 0 // 所有分页渲染次数
export async function doPrintSilence(menuName) {
  // 获取菜单xml名称
  /*  getMenunameByCode(menuName).then((res) => {
    removeCanvasDom()
    let params = `?_u=slip-${res.data}`
    let url = `/ureport/pdf/show${params}`
    pdfjs.GlobalWorkerOptions.workerSrc = pdfjsWorker
    pdfjs.getDocument({ url }).promise.then(function getPdfHelloWorld(pdf) {
      let pageNum = pdf.numPages
      console.log('页数:' + pageNum)
      console.log(document)
      //处理
      for (let i = 1; i <= pageNum; i++) {
        let canvas = document.createElement('canvas')
        let id = 'pageNum' + i
        canvas.id = id
        canvasImgs.push(id)
        document.querySelector('body').appendChild(canvas)
        let context = canvas.getContext('2d')
        renderImg(pdf, i, context, pageNum, canvasImgs, params)
      }
    })
  }) */
}

//渲染生成图片
function renderImg(
  pdfFile,
  pageNumber,
  canvasContext,
  total,
  canvasImgs,
  params
) {
  let scale = 3 //设置缩放比例，越大生成图片越清晰
  pdfFile.getPage(pageNumber).then(function (page) {
    //逐页解析PDF
    let viewport = page.getViewport({ scale }) // 页面缩放比例
    let newcanvas = canvasContext.canvas
    //设置canvas真实宽高
    newcanvas.width = viewport.width
    newcanvas.height = viewport.height

    //设置canvas在浏览中宽高
    newcanvas.style.width = '100%'
    newcanvas.style.height = '100%'
    newcanvas.style.display = 'none'

    let renderContext = {
      canvasContext: canvasContext,
      viewport: viewport,
    }
    //渲染生成
    page.render(renderContext).promise.then(function () {
      renderTimes++
      if (renderTimes === total) {
        renderTimes = 0
        toPrint(canvasImgs, params)
      }
    })
  })
}

// 打印
async function toPrint(canvasImgs, params) {
  console.log('准备打印')
  // 获取打印配置
  let res = await getExportConfig(params)
  // 打印配置
  let printConfig = res.paper
  let LODOP = getLodop()
  if (!LODOP) {
    return
  }
  LODOP.PRINT_INIT('')
  /**
   * SET_PRINT_PAGESIZE(intOrient,intPageWidth,intPageHeight,strPageName);
   *
   * 参数含义：
   * intOrient：打印方向及纸张类型
   * 值为1---纵向打印，固定纸张；
   * 值为2---横向打印，固定纸张；
   * 值为3---纵向打印，宽度固定，高度按打印内容的高度自适应；
   * 0(或其它)----打印方向由操作者自行选择或按打印机缺省设置。
   * intPageWidth：
   * 纸张宽，单位为0.1mm 譬如该参数值为45，则表示4.5mm,计量精度是0.1mm。
   *
   * intPageHeight：
   * 固定纸张时该参数是纸张高；高度自适应时该参数是纸张底边的空白高，计量单位与纸张宽一样。
   *
   * strPageName：
   * 纸张名，必须intPageWidth等于零时本参数才有效，有如下选择：
   * Letter, LetterSmall, Tabloid, Ledger, Legal,Statement, Executive,
   * A3, A4, A4Small, A5, B4, B5, Folio, Quarto, qr10X14, qr11X17, Note,
   * Env9, Env10, Env11, Env12,Env14, Sheet, DSheet, ESheet
   * */
  LODOP.SET_PRINT_PAGESIZE(
    printConfig.orientation === 'portrait' ? 1 : 2,
    0,
    0,
    printConfig.paperType
  )
  LODOP.SET_PRINT_STYLE('Stretch', 2)
  // 分页设置
  for (let i = 0; i < canvasImgs.length; i++) {
    let canvasEle = document.getElementById(canvasImgs[i])
    let dataUrl = canvasEle.toDataURL()
    LODOP.ADD_PRINT_IMAGE(
      '0mm',
      '0mm',
      'RightMargin:0mm',
      'BottomMargin:0mm',
      `<img src="${dataUrl}">`
    )
    //分页
    LODOP.NewPageA()
  }
  LODOP.SET_PRINT_MODE('CATCH_PRINT_STATUS', true)
  // 静默打印
  let prt = LODOP.PRINT()
  // 预览打印
  // let prt = LODOP.PREVIEW()
  return prt
}

// 移除旧的的canvas节点
function removeCanvasDom() {
  for (let i = 0; i < canvasImgs.length; i++) {
    let canvasDom = document.getElementById(canvasImgs[i])
    if (canvasDom) {
      canvasDom.remove()
    }
  }
  canvasImgs = []
}
